package com.stone.redis.lock.app.service;

import com.stone.redis.lock.domain.bo.LockInfo;
import com.stone.redis.lock.service.impl.FairLockServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 公平锁测试
 *
 * @author Mr_wenpan@163.com 2021/07/27 17:29
 */
@Slf4j
@Service
public class RedisFairLockTestService {

    @Autowired
    private FairLockServiceImpl fairLockService;

    public void test() throws InterruptedException {
        LockInfo lockInfo = LockInfo.builder().name("stone:test:redis:test-lock")
                .waitTime(60L).leaseTime(300L).timeUnit(TimeUnit.SECONDS).build();
        fairLockService.setLockInfo(lockInfo);
        boolean isLocked = fairLockService.lock();
        if (isLocked) {
            try {
                System.out.println("获取锁成功！");
            } finally {
                fairLockService.releaseLock();
            }
        } else {
            log.warn("等待 {} 秒后，获取锁 {} 仍然失败！", lockInfo.getWaitTime(), lockInfo.getName());
        }

    }
}
